var app = getApp();
var time = require('../../utils/util.js');
Page({
  data: {
    getBooksByCondition: app.globalData.bookUrl + '/book/getBooks.do',
    getBookType: app.globalData.bookUrl + '/book/bookType.do',
    index: 0,
    array1: ['全部', '架上', '已借出', '丢失'],
    bookTypeList: [],
    bookName4Search: '',
    currentPage: 1,
    booklist: [],
    index: 0,
    index1: 0,
    winWidth: 0,
    winHeight: 0,
    height: 0
  },
  onLoad: function(options) {
    var that = this;
    var getBookType = that.data.getBookType;
    var getBooksByCondition = that.data.getBooksByCondition; //获取图书URL
    /** 获取系统信息 */
    wx.getSystemInfo({
      success: function(res) {
        that.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight
        });
      }
    });
    var query = wx.createSelectorQuery();
    query.select('.entirety').boundingClientRect()
    query.exec(function(res) {
      console.log(res[0].height);
      that.setData({
        height: res[0].height
      })
    })
    that.getBookType(getBookType);
  },
  onShow: function() {
    app.scanFlag = true
  },
  // 下拉刷新
  onPullDownRefresh: function() {
    // 显示顶部刷新图标
    wx.showNavigationBarLoading();
    this.setData({
      bookName4Search: "",
      currentPage: 1,
      booklist: [],
      index: 0,
      index1: 0
    });
    wx.showNavigationBarLoading({
      title: '正在刷新',
    })
    // 页数+1
    this.getBooksByCondition();
  },

  onReachBottom: function() {
    var that = this;
    var result = that.data.booklist;
    if (result.length == that.data.totalElements) { //最大数值
      wx.showToast({
        title: "已到达底部",
        icon: "success",
        duration: 1500
      });
      return false;
    } else {
      // 显示加载图标
      // wx.showLoading({
      //   title: '玩命加载中',
      //   duration: 5500
      // })
      // 页数+1
      that.getBooksByCondition();
    }

  },
  bindscan: function() {
    console.log('扫码')
    wx.scanCode({
      onlyFromCamera: true,
      success(res) {
        var qcodeurl = res.result
        var isQcodeurl = qcodeurl.split('?')[0]
        qcodeurl = qcodeurl.split('?')[1]
        qcodeurl = qcodeurl + "&scanflag=1"
        if (isQcodeurl == "https://hptupgrade.chinasafe.com.cn/book/isWeChat.do") {
          wx.navigateTo({
            url: "../details/borrow/borrow?" + qcodeurl + "&isBackEstimate=no"
          })
        } else {
          wx.showToast({
            title: "无效二维码",
            icon: "warn",
            image: '../../images/icon/fail.png',
          });
        }
      }
    })
  },

  getBookType: function(getBookType) {
    var that = this;
    wx.request({
      url: getBookType,
      data: {},
      method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function(res) {
        that.showBookType(res.data.data); //向前台传递数据
        that.getBooksByCondition(); //获取全部图书
      },
      fail: function(error) {
        // fail
        console.log(error)
      }
    })
  },
  getBooksByCondition: function() {
    var that = this;
    var getBooksByCondition = that.data.getBooksByCondition;
    var bookTypeId = that.data.index;
    var bookTypeState = that.data.index1;
    var currentPage = that.data.currentPage;
    var bookName = that.data.bookName4Search;
    wx.request({
      url: getBooksByCondition,
      data: {
        bookTypeId: bookTypeId,
        bookState: bookTypeState,
        bookName: bookName,
        currentPage: currentPage
      },
      method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function(res) {
        that.showAllBooksByCondition(res.data.data); //向前台传递数据
        if (res.data.data != null) {
          that.setData({
            currentPage: currentPage + 1,
            totalElements: res.data.data.totalElements
          });
        }
      },
      fail: function(error) {
        // fail
        console.log(error)
      }
    })
    wx.hideNavigationBarLoading();
    wx.stopPullDownRefresh();
    // }
  },

  showBookType: function(allBookType) {
    var that = this;
    var bookType = [];
    bookType.push("全部");
    if (allBookType.size > 0) {
      for (var idx in allBookType.content) {
        var content = allBookType.content[idx];
        var bookTypeName = content.bookTypeName;
        bookType.push(bookTypeName);
        that.setData({
          bookTypeList: bookType
        });
      }
    } else {
      console.log("没有该分类");
    }
  },
  showAllBooksByCondition: function(allBooksByCondition) {
    var that = this;
    var books = that.data.booklist;
    if (allBooksByCondition != null) {
      for (var idx in allBooksByCondition.content) {
        var content = allBooksByCondition.content[idx];
        var bookImgSource = app.globalData.bookUrl + content.bookImg + '?' + Math.random() / 9999;
        var createTimeSource = time.formatTime(content.createTime, 'Y-M-D h:m:s');
        var bookTypeIdSource = content.bookTypeId;
        var bookStateSource = content.bookState;
        var bookState;
        var color;
        var types = that.data.bookTypeList;
        var typeName = types[bookTypeIdSource];
        switch (bookStateSource) {
          case "1":
            bookState = "架上";
            color = "#2bca6e";
            break;
          case "2":
            bookState = "已借出";
            color = "#fe8b23";
            break;
          case "3":
            bookState = "丢失";
            color = "#ca2222";
            break;
        }
        var temp = {
          bookId: content.bookId,
          bookImg: bookImgSource,
          bookName: content.bookName,
          createTime: createTimeSource,
          bookAuthor: content.bookAuthor,
          bookType: typeName,
          bookState: bookState,
          color: color
        }
        books.push(temp);
        that.setData({
          booklist: books
        });
        wx.hideLoading({
          title: '玩命加载中',
        })
        wx.hideNavigationBarLoading() //完成停止加载
      }
    } else {
      wx.showToast({
        title: "未查到",
        icon: "warn",
        duration: 1500
      });
    }
  },
  bindPickerChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    var that = this;
    that.setData({
      index: e.detail.value,
      currentPage: 1,
      booklist: [],
    })
    that.getBooksByCondition()

  },
  bindPickerChange1: function(e) {
    console.log('picker1发送选择改变，携带值为', e.detail.value)
    var that = this;
    this.setData({
      index1: e.detail.value,
      currentPage: 1,
      booklist: [],
    })
    that.getBooksByCondition(); //根据类别获取全部图书

  },
  navigateToee: function(e) {
    var bookId = e.currentTarget.dataset.bookid;
    var bookState = e.currentTarget.dataset.bookstate;
    var bookType = e.currentTarget.dataset.booktype;
    if (bookState == "架上") {
      wx.navigateTo({
        url: "../details/borrow/borrow?bookId=" + bookId + "&scanflag=2&bookType=" + bookType +"&isBackEstimate=no"
      })
    } else {
      wx.navigateTo({
        url: "../details/loan/loan?bookId=" + bookId + "&bookType=" + bookType + "&isBackEstimate=no"
      })
    }
  },
  //获取搜索框内容
  bookNameInput: function(e) {
    this.setData({
      bookName4Search: e.detail.value
    })
  },
  /**
   * 按书名模糊查询
   */
  searchByBookName: function() {
    var that = this;
    console.log('搜索框')
    that.setData({
      booklist: [],
      currentPage: 1
    });
    that.getBooksByCondition(); //根据类别获取全部图书
  },

})